<?php
/**
 * @Author: gan
 * @Description: 阿里云短信
 * @File:  AliyunSms
 * @Version: 1.0.0
 * @Date: 2021/12/27 9:15 上午
 */
declare(strict_types=1);

namespace RX\Component\Sms\Impl;

use AlibabaCloud\Client\AlibabaCloud;
use RX\Enums\SmsEnum;
use RX\Exception\BizException;
use RX\Helpers\StringHelper;

class AliyunImpl implements SmsInterface
{
    private string $regionId = "cn-shanghai";
    private string $secretId;
    private string $secretKey;

    public function __construct(array $config = [])
    {
        if (empty($config)) {
            $config = StringHelper::config('sms.aliyun');
        }
        $this->secretId  = $config['secretId'];
        $this->secretKey = $config['secretKey'];
        AlibabaCloud::accessKeyClient($this->secretId, $this->secretKey)->regionId($this->regionId)->asDefaultClient();
    }

    public function send(string $mobile, string $sign, string $template, array $templateParams = [])
    {
        $result     = AlibabaCloud::rpc()
                                  ->product('Dysmsapi')
                                  ->scheme('https')
                                  ->version('2017-05-25')
                                  ->action('SendSms')
                                  ->method('POST')
                                  ->host('dysmsapi.aliyuncs.com')
                                  ->options([
                                      'query' => [
                                          'RegionId'      => $this->regionId,
                                          'PhoneNumbers'  => $mobile,
                                          'SignName'      => $sign,
                                          'TemplateCode'  => $template,
                                          'TemplateParam' => json_encode($templateParams),
                                      ],
                                  ])
                                  ->request();
        $resultData = $result->toArray();
        if (!isset($resultData['Code']) || $resultData['Code'] != 'OK') {
            $msg = $resultData['Message'] ?? null;
            throw new BizException(SmsEnum::class, SmsEnum::SMS_FAIL, $msg);
        }
        return $resultData;
    }
}
